package com.xiaochong.tir.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.tir.api.component.HbaseBaseQueryComponent;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.api.service.WebSocketService;
import com.xiaochong.tir.api.thread.KLineActionOfTwoDayThread;
import com.xiaochong.tir.api.util.ApiVersion;
import com.xiaochong.tir.api.util.ListSortUtil;
import com.xiaochong.tir.api.util.TimeSeconds;
import com.xiaochong.tir.common.data.hbasepo.TradesHistory;
import com.xiaochong.tir.common.data.hbasepo.TradesHistoryCountFive;
import com.xiaochong.tir.common.data.hbasepo.TradesToKLine;
import com.xiaochong.tir.common.data.mapper.ExchangeDimensionMiddleMapper;
import com.xiaochong.tir.common.data.mapper.ExchangeInfoMapper;
import com.xiaochong.tir.common.data.mapper.ExchangeTransactionpairMiddleMapper;
import com.xiaochong.tir.common.data.mapper.KLineMapper;
import com.xiaochong.tir.common.data.po.ExchangeDimensionMiddle;
import com.xiaochong.tir.common.data.po.ExchangeInfo;
import com.xiaochong.tir.common.data.po.ExchangeTransactionpairMiddle;
import com.xiaochong.tir.common.data.po.KLine;
import com.xiaochong.tir.common.data.vo.ApiResultVo;
import com.xiaochong.tir.common.data.vo.ApiTradesHistoryVo;
import com.xiaochong.tir.common.data.vo.ApiWebSocketVo;
import com.xiaochong.tir.common.util.ApiResultCodeUtils;
import com.xiaochong.tir.common.util.DateUtils;
import com.xiaochong.tir.common.util.HbaseTableUtils;
import com.xiaochong.tir.common.util.RedisKeysUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.util.JSONTokener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * 通证指数
 * @author MengXiangDong
 */
@RestController
@Api(value = "k线")
@RequestMapping(value =ApiVersion.API_V1_PREFIX+"/k")
public class WebSocketController {

	@Autowired
	private WebSocketService webSocketService;

	@Autowired
	private RedisServer redisServer;

	@Autowired
	private HbaseBaseQueryComponent hbaseBaseQueryComponent;

	@Autowired
	private ExchangeInfoMapper exchangeInfoMapper;

	@Autowired
	private ExchangeDimensionMiddleMapper exchangeDimensionMiddleMapper;

	@Autowired
	private ExchangeTransactionpairMiddleMapper exchangeTransactionpairMiddleMapper;

	@Autowired
	private KLineMapper kLineMapper;

	/*ExecutorService executorService = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors()*2+1,
			Runtime.getRuntime().availableProcessors()*2+1, 0L, TimeUnit.MILLISECONDS,
			new ArrayBlockingQueue<Runnable>(1000),
			new ThreadPoolExecutor.CallerRunsPolicy());*/
	//ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(100,100,100,new TimeUnit(),new ArrayBlockingQueue<Runnable>(100));

	//k线数据-K线图
	@ApiOperation(value = "k线数据-K线图按照最后时间戳和条数查询" , notes = "k线数据-K线图")
	@PostMapping("kActionLongTime")
	public ApiResultVo kActionLongTime(@RequestParam(value = "LongTime", required = false) String LongTime,@RequestParam(value = "exchangeId", required = false) String exchangeId,@RequestParam(value = "transactionName", required = false) String transactionName
			,@RequestParam(value = "num", required = false) Integer num) throws Exception {
		ApiResultVo resultVo = new ApiResultVo();
		Long nowTImeres = Long.valueOf(LongTime);
		List<String> resultList=new ArrayList<>();
		try {
			String grailStr=null;
			TradesToKLine tradesToKLine;
			LocalDateTime timeres = DateUtils.getDateTimeOfTimestamp(nowTImeres);
			for(int i=1;i<=num.intValue();i++){
				timeres = timeres.minusMinutes(i);
				String lastRowKey = DateUtils.localDateTimeFormatString(timeres,DateUtils.format_ymdhm);//当前时间转成分钟
				String rowKey = exchangeId+"@"+transactionName+"@"+lastRowKey;
				grailStr = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.API_SERVICE_K_ACTION_TABLE_NAME
						, HbaseTableUtils.API_SERVICE_K_ACTION_TABLE_NAME_FAMILY
						, HbaseTableUtils.API_SERVICE_K_ACTION_QUALIFIER
						, rowKey
				);
				if (grailStr!=null){
					Object listArray = new JSONTokener(grailStr).nextValue();
					if(listArray instanceof  net.sf.json.JSONArray){//老数据兼容问题
						JSONArray jsonArray = JSON.parseArray(grailStr);
						tradesToKLine = new TradesToKLine();
						tradesToKLine.setTimestamp(jsonArray.getString(0));
						tradesToKLine.setOpenPrice(jsonArray.getString(1));
						tradesToKLine.setHighestPrice(jsonArray.getString(2));
						tradesToKLine.setLowestPrice(jsonArray.getString(3));
						tradesToKLine.setClosePrice(jsonArray.getString(4));
						tradesToKLine.setVolume(jsonArray.getString(5));
						resultList.add(JSON.toJSONString(tradesToKLine));
					}else{
						resultList.add( grailStr );
					}
				}
			}
			Collections.reverse( resultList );
			resultVo.setCode( ApiResultCodeUtils.BASE_SUCCESS.getCode());
			resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
			resultVo.setTradeId(LogTrace.getTrace().getTraceId());
			resultVo.setData( resultList );
			resultVo.setPages( resultList.size() );
		}catch (Exception e){
			e.printStackTrace();
			LogTrace.error("k线数据-K线图", e);
		}
		return resultVo;
	}
	@ApiOperation(value = "k线数据-K线图-两天数据" , notes = "k线数据-K线图-两天数据")
	@PostMapping("kActionOfTwoDay")
	public ApiResultVo kActionOfTwoDay(@RequestParam(value = "kDate", required = false) String kDate,@RequestParam(value = "exchangeId", required = false) String exchangeId,@RequestParam(value = "transactionName", required = false) String transactionName) throws Exception {
		ApiResultVo resultVo = new ApiResultVo();
		//Long nowTImeres = DateUtils.getLongTIme( kDate )+86400000;
		List<String> resultList=new ArrayList<>();
		//获取传入时间日期
		Long nowTImeres = DateUtils.getLongTIme(kDate);
		LocalDateTime time = DateUtils.getDateTimeOfTimestamp( nowTImeres);
		try {
			List<String> resultListToday=new ArrayList<>();
			List<String> resultListYesday=new ArrayList<>();
			CountDownLatch countDownLatch = new CountDownLatch(2);
			//分别查询今天和昨天数据，两个线程

			String dateToday = DateUtils.localDateTimeFormatString(time,DateUtils.format_ymds);
			String dateYesday = DateUtils.localDateTimeFormatString(time.minusDays(1),DateUtils.format_ymds);
			Thread threadToday = new Thread(new KLineActionOfTwoDayThread(resultListToday,countDownLatch,dateToday,Integer.valueOf(exchangeId),transactionName));
			threadToday.start();
			Thread threadYesday = new Thread(new KLineActionOfTwoDayThread(resultListYesday,countDownLatch,dateYesday,Integer.valueOf(exchangeId),transactionName));
			threadYesday.start();
//			executorService.execute(new KLineActionOfTwoDayThread(resultListToday,countDownLatch,dateToday,Integer.valueOf(exchangeId),transactionName));
//			executorService.execute(new KLineActionOfTwoDayThread(resultListYesday,countDownLatch,dateYesday,Integer.valueOf(exchangeId),transactionName));
			countDownLatch.await();
			resultList.addAll(resultListYesday);
			resultList.addAll(resultListToday);
			/*String grailStr=null;
			TradesToKLine tradesToKLine;
			LocalDateTime timeres = DateUtils.getDateTimeOfTimestamp( nowTImeres);
			for(int i=0;i<2880;i++){
				timeres = timeres.minusMinutes(1);
				String lastRowKey = DateUtils.localDateTimeFormatString(timeres,DateUtils.format_ymdhm);//当前时间转成分钟
				String rowKey = exchangeId+"@"+transactionName+"@"+lastRowKey;
                grailStr = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.API_SERVICE_K_ACTION_TABLE_NAME
						, HbaseTableUtils.API_SERVICE_K_ACTION_TABLE_NAME_FAMILY
						, HbaseTableUtils.API_SERVICE_K_ACTION_QUALIFIER
						, rowKey
				);
				if (grailStr!=null){
					Object listArray = new JSONTokener(grailStr).nextValue();
					if(listArray instanceof  net.sf.json.JSONArray){//老数据兼容问题
						JSONArray jsonArray = JSON.parseArray(grailStr);
						tradesToKLine = new TradesToKLine();
						tradesToKLine.setTimestamp(jsonArray.getString(0));
						tradesToKLine.setOpenPrice(jsonArray.getString(1));
						tradesToKLine.setHighestPrice(jsonArray.getString(2));
						tradesToKLine.setLowestPrice(jsonArray.getString(3));
						tradesToKLine.setClosePrice(jsonArray.getString(4));
						tradesToKLine.setVolume(jsonArray.getString(5));
						resultList.add(JSON.toJSONString(tradesToKLine));
					}else{
						resultList.add( grailStr );
					}
				}
			}

			Collections.reverse( resultList );*/
			resultVo.setCode( ApiResultCodeUtils.BASE_SUCCESS.getCode());
			resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
			resultVo.setTradeId(LogTrace.getTrace().getTraceId());
			resultVo.setData( resultList );
			resultVo.setPages( resultList.size() );
		}catch (Exception e){
			e.printStackTrace();
			LogTrace.error("k线数据-K线图", e);
			resultVo.setCode( ApiResultCodeUtils.SYSTEM_ERROR.getCode());
			resultVo.setMessage(ApiResultCodeUtils.SYSTEM_ERROR.getMsg());
		}
		return resultVo;
	}
	//k线数据-K线图
	@ApiOperation(value = "k线数据-K线图" , notes = "k线数据-K线图")
	@PostMapping("kAction")
	public ApiResultVo kAction(@RequestParam(value = "kDate", required = false) String kDate,@RequestParam(value = "exchangeId", required = false) String exchangeId,@RequestParam(value = "transactionName", required = false) String transactionName) throws Exception {
		ApiResultVo resultVo = new ApiResultVo();
		Long nowTImeres = DateUtils.getLongTIme( kDate )+86400000;
		List<String> resultList=new ArrayList<>(  );
		try {
			String grailStr=null;
			int d=0;
			TradesToKLine tradesToKLine;
			while (true){
                LocalDateTime timeres = DateUtils.getDateTimeOfTimestamp( nowTImeres-d );
				String lastRowKey = DateUtils.localDateTimeFormatString(timeres,DateUtils.format_ymdhm);//当前时间转成分钟
				String rowKey = exchangeId+"@"+transactionName+"@"+lastRowKey;
				grailStr = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.API_SERVICE_K_ACTION_TABLE_NAME
						, HbaseTableUtils.API_SERVICE_K_ACTION_TABLE_NAME_FAMILY
						, HbaseTableUtils.API_SERVICE_K_ACTION_QUALIFIER
						, rowKey
				);
				d+=60000;
				if (grailStr!=null){
					Object listArray = new JSONTokener(grailStr).nextValue();
					if(listArray instanceof  net.sf.json.JSONArray){//老数据兼容问题
						JSONArray jsonArray = JSON.parseArray(grailStr);
						tradesToKLine = new TradesToKLine();
						tradesToKLine.setTimestamp(jsonArray.getString(0));
						tradesToKLine.setOpenPrice(jsonArray.getString(1));
						tradesToKLine.setHighestPrice(jsonArray.getString(2));
						tradesToKLine.setLowestPrice(jsonArray.getString(3));
						tradesToKLine.setClosePrice(jsonArray.getString(4));
						tradesToKLine.setVolume(jsonArray.getString(5));
						/*try {
							tradesToKLine.setPriceCny(jsonArray.getString(7));
						}catch (Exception e){
							tradesToKLine.setPriceCny(jsonArray.getString(4));
							e.printStackTrace();
						}*/
						resultList.add(JSON.toJSONString(tradesToKLine));
					}else{
						resultList.add( grailStr );
					}
				}
				if(d>=86400000){
				    break;
                }
			}

			Collections.reverse( resultList );
			resultVo.setCode( ApiResultCodeUtils.BASE_SUCCESS.getCode());
			resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
			resultVo.setTradeId(LogTrace.getTrace().getTraceId());
			resultVo.setData( resultList );
			resultVo.setPages( resultList.size() );
		}catch (Exception e){
			e.printStackTrace();
			LogTrace.error("k线数据-K线图", e);
		}
		return resultVo;
	}

	//k线数据-K线图
	@ApiOperation(value = "k线数据-K线图最新一次数据" , notes = "k线数据-K线图最新一次数据")
	@PostMapping("NewkAction")
	public ApiResultVo NewkAction(@RequestParam(value = "exchangeId", required = false) String exchangeId,@RequestParam(value = "transactionName", required = false) String transactionName) throws Exception {
		ApiResultVo resultVo = new ApiResultVo();
		try {
			String grailStr=null;
			Long nowTImeres =DateUtils.getCurrentDataLong();;
			/*while (true){
				nowTImeres=nowTImeres-60000;
				LocalDateTime timeres = DateUtils.getDateTimeOfTimestamp( nowTImeres );
				String lastRowKey = DateUtils.localDateTimeFormatString(timeres,DateUtils.format_ymdhm);//当前时间转成分钟
				String rowKey = exchangeId+"@"+transactionName+"@"+lastRowKey;
				grailStr = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.API_SERVICE_K_ACTION_TABLE_NAME
						, HbaseTableUtils.API_SERVICE_K_ACTION_TABLE_NAME_FAMILY
						, HbaseTableUtils.API_SERVICE_K_ACTION_QUALIFIER
						, rowKey
				);
				if (grailStr!=null){
					break;
				}
			}*/
			String klineRedis = RedisKeysUtils.API_SERVICE_K_ACTION_TRADES_TWO+"@"+exchangeId+"@"+transactionName;
			grailStr = redisServer.get(klineRedis);
			resultVo.setCode( ApiResultCodeUtils.BASE_SUCCESS.getCode());
			resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
			resultVo.setTradeId(LogTrace.getTrace().getTraceId());
			resultVo.setData( grailStr );
		}catch (Exception e){
			e.printStackTrace();
			LogTrace.error("k线数据-K线图", e);
		}
		return resultVo;
	}

	//k线数据-K线图
	@ApiOperation(value = "交易所列表" , notes = "交易所列表（参数：交易所id，交易对名称，维度）")
	@PostMapping("transactions")
	public ApiResultVo transactions() throws Exception {
		ApiResultVo resultVo = new ApiResultVo();
		try {
			ExchangeInfo exchangeInfo=new ExchangeInfo();
			exchangeInfo.setEnableFlag( true );
			exchangeInfo.setDeleteFlag( false );
			exchangeInfo.setKlineStatus( true );

			List<ExchangeInfo> infoList=exchangeInfoMapper.selectByEntityList( exchangeInfo );
			List<ExchangeInfo> infoList2=new ArrayList<>(  );
			List<ExchangeInfo> infoList3=new ArrayList<>(  );
			List<ExchangeInfo> infoList4=new ArrayList<>(  );

			for (int i=0;i<infoList.size();i++){
				ExchangeInfo info = infoList.get( i );
				if(infoList.get( i ).getSort()!=null){
					infoList2.add( info );
				}else{
					infoList3.add( info );
				}
			}
			ListSortUtil sortUtil=new ListSortUtil();
			sortUtil.mySort( infoList2,"sort","asc" );


			for(int i=0;i<infoList3.size();i++){
				ExchangeInfo info=new ExchangeInfo();
				info.setExchangeName( infoList3.get( i ).getExchangeName() );
				info.setId( infoList3.get( i ).getId() );
				infoList4.add( info );
				infoList3.get( i ).setExchangeName( infoList3.get( i ).getExchangeName().toUpperCase() );
			}
			sortUtil.mySort( infoList3,"exchangeName","asc" );
			for(int i=0;i<infoList3.size();i++){
				for (int j=0;j<infoList4.size();j++){
					if(infoList4.get( j ).getId() .equals(   infoList3.get( i ).getId()) ){
						infoList3.get( i ).setExchangeName( infoList4.get( j ).getExchangeName() );
					}
				}
			}
			infoList2.addAll( infoList3 );
			resultVo.setCode( ApiResultCodeUtils.BASE_SUCCESS.getCode());
			resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
			resultVo.setTradeId(LogTrace.getTrace().getTraceId());
			resultVo.setData( infoList2 );
			resultVo.setTotal( infoList2.size() );
		}catch (Exception e){
			e.printStackTrace();
			LogTrace.error("k线数据-K线图", e);
		}
		return resultVo;
	}
	//k线数据-K线图
	@ApiOperation(value = "根据交易所获取纬度列表" , notes = "根据交易所获取纬度列表（参数：交易所id）")
	@PostMapping("dimensions")
	public ApiResultVo dimensions(@RequestParam(value = "exchangeId", required = false) int exchangeId) throws Exception {
		ApiResultVo resultVo = new ApiResultVo();
		try {
			ExchangeDimensionMiddle exchangeDimensionMiddle=new ExchangeDimensionMiddle();
			exchangeDimensionMiddle.setEnableFlag( true );
			exchangeDimensionMiddle.setExchangeId( exchangeId );
			List<ExchangeDimensionMiddle> middleList=exchangeDimensionMiddleMapper.selectByEntityList( exchangeDimensionMiddle );

			for (int i=0;i<middleList.size();i++){
				ExchangeDimensionMiddle middle=middleList.get( i );
				int time=0;
				try {
					time=TimeSeconds.getValue(middle.getDimensionName());
				}catch (Exception e){
				}
				middle.setSeconds(time);
			}

			ListSortUtil sortUtil=new ListSortUtil();
			sortUtil.mySort( middleList,"seconds","asc" );
			resultVo.setCode( ApiResultCodeUtils.BASE_SUCCESS.getCode());
			resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
			resultVo.setTradeId(LogTrace.getTrace().getTraceId());
			resultVo.setData( middleList );
			resultVo.setTotal( middleList.size() );
		}catch (Exception e){
			e.printStackTrace();
			LogTrace.error("k线数据-K线图", e);
		}
		return resultVo;
	}

	//k线数据-K线图
	@ApiOperation(value = "根据交易所获取交易对列表" , notes = "根据交易所获取交易对列表（参数：交易所id）")
	@PostMapping("allExchange")
	public ApiResultVo allExchange(@RequestParam(value = "exchangeId", required = false) int exchangeId) throws Exception {
		ApiResultVo resultVo = new ApiResultVo();
		try {
			ExchangeTransactionpairMiddle exchangeTransactionpairMiddle=new ExchangeTransactionpairMiddle();
			exchangeTransactionpairMiddle.setEnableFlag( true );
			exchangeTransactionpairMiddle.setExchangeId( exchangeId );
			List<ExchangeTransactionpairMiddle> exchangeMiddleList = exchangeTransactionpairMiddleMapper.selectByEntityList( exchangeTransactionpairMiddle );
			resultVo.setCode( ApiResultCodeUtils.BASE_SUCCESS.getCode());
			resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
			resultVo.setTradeId(LogTrace.getTrace().getTraceId());
			resultVo.setData( exchangeMiddleList );
			resultVo.setTotal( exchangeMiddleList.size() );
		}catch (Exception e){
			e.printStackTrace();
			LogTrace.error("k线数据-K线图", e);
		}
		return resultVo;
	}

	//k线数据-K线图大纬度
	@ApiOperation(value = "k线数据-K线图大纬度" , notes = "k线数据-K线图大纬度")
	@PostMapping("daykline")
	public ApiResultVo<KLine> daykline(@RequestParam(value = "exchangeId", required = false) int exchangeId,@RequestParam(value = "transactionName", required = false) String transactionName) throws Exception {
		ApiResultVo resultVo = new ApiResultVo();
		try {
			// 日K数据加入redis
			String key = "daykline_"+exchangeId+"_"+transactionName;
			//缓存过期时间
			long expireTime = 60*60*3;
			List<KLine> kList;
			String data ;
			data = redisServer.get(key);
			if(data!=null){
				LogTrace.infoKvs("daykline命中缓存" ,"exchangeId" , exchangeId+"","transactionName" , transactionName );
				kList = JSON.parseArray(data , KLine.class);
			}else{
				LogTrace.infoKvs("daykline查询" ,"exchangeId" , exchangeId+"","transactionName" , transactionName );

				KLine kLine=new KLine();
				kLine.setExchangeId( exchangeId );
				kLine.setTransationPairName(  transactionName);
				kList = kLineMapper.selectKline12h( kLine );

				//日期转时间戳
				for (int i=0;i<kList.size();i++){
					kList.get( i ).setKDate( DateUtils.getLongTIme2(kList.get( i ).getKDate()).toString() );
				}
				if(kList.size() >0){
					data = JSON.toJSONString(kList);
					redisServer.set(key , data ,expireTime);
				}
			}
			resultVo.setCode( ApiResultCodeUtils.BASE_SUCCESS.getCode());
			resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
			resultVo.setTradeId(LogTrace.getTrace().getTraceId());
			resultVo.setData( kList );
			resultVo.setTotal( kList == null ? 0 : kList.size() );
		}catch (Exception e){
			e.printStackTrace();
			LogTrace.error("K线图大纬度", e);
		}
		return resultVo;
	}

	//历史交易列表
	@ApiOperation(value = "历史交易列表" , notes = "历史交易列表")
	@PostMapping("tranesList")
	public ApiResultVo<KLine> tranesList(@RequestParam(value = "exchangeId", required = false) int exchangeId,@RequestParam(value = "transactionName", required = false) String transactionName) throws Exception {
		ApiResultVo resultVo = new ApiResultVo();
		try {

			String Rediskey = RedisKeysUtils.API_SERVICE_TRADES_ALL_DATA+"@"+exchangeId+"@"+transactionName;
			String API_SERVICE_TRADES_ALL_DATA=redisServer.get(Rediskey);
			if(org.apache.commons.lang3.StringUtils.isNotBlank(API_SERVICE_TRADES_ALL_DATA)){
				List<ApiTradesHistoryVo> tradesHistoryVos = new ArrayList<>();
				ApiTradesHistoryVo apiTradesHistoryVo;
				List<TradesHistory> tradesHistoryList = JSON.parseArray(API_SERVICE_TRADES_ALL_DATA,TradesHistory.class);
				if(tradesHistoryList!=null && tradesHistoryList.size()>0){
					for(TradesHistory tradesHistory :tradesHistoryList){
						apiTradesHistoryVo = new ApiTradesHistoryVo();
						apiTradesHistoryVo.setAmount(tradesHistory.getAmount().stripTrailingZeros().toPlainString());
						apiTradesHistoryVo.setPrice(tradesHistory.getPrice().stripTrailingZeros().toPlainString());
						apiTradesHistoryVo.setTimestamp(tradesHistory.getTimestamp());
                        apiTradesHistoryVo.setBuyOrSellFlag(tradesHistory.getSide());
						tradesHistoryVos.add(apiTradesHistoryVo);
					}
				}
				resultVo.setData( tradesHistoryVos );
			}
			resultVo.setCode( ApiResultCodeUtils.BASE_SUCCESS.getCode());
			resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
			resultVo.setTradeId(LogTrace.getTrace().getTraceId());
		}catch (Exception e){
			e.printStackTrace();
			LogTrace.error("K线图大纬度", e);
		}
		return resultVo;
	}

	@ApiOperation(value = "表头请求数据" , notes = "表头请求数据")
	@PostMapping("rise")
	public ApiResultVo rise(@RequestParam(value = "exchangeId", required = false) String exchangeId,@RequestParam(value = "transactionId", required = false) Integer transactionId) throws Exception {
		ApiResultVo resultVo = new ApiResultVo();
		try {
			ExchangeTransactionpairMiddle query = new ExchangeTransactionpairMiddle();;
			query.setTransactionId(transactionId);
			query.setExchangeId(Integer.valueOf(exchangeId));
			ExchangeTransactionpairMiddle exchangeTransactionpairMiddle = exchangeTransactionpairMiddleMapper.selectByEntity(query);
			if(exchangeTransactionpairMiddle == null || !exchangeTransactionpairMiddle.getEnableFlag()){
				LogTrace.info("rise","exchangeTransactionpairMiddle",transactionId+"查询不可用");
				resultVo.setCode( ApiResultCodeUtils.SYSTEM_NULL.getCode());
				resultVo.setMessage(ApiResultCodeUtils.SYSTEM_NULL.getMsg());
				resultVo.setTradeId(LogTrace.getTrace().getTraceId());
				return resultVo;
			}
			//redis
			Long nowTImeres = DateUtils.getCurrentDataLong();
			LocalDateTime timeres = DateUtils.getDateTimeOfTimestamp( nowTImeres	 );
			String redisPriceDate = DateUtils.localDateTimeFormatString(timeres,DateUtils.format_ymds);
			String Rediskey = RedisKeysUtils.API_SERVICE_K_ACTION_ALL_DATA_PRICE + "@" + exchangeId + "@" + exchangeTransactionpairMiddle.getTransactionName();
			String API_SERVICE_K_ACTION_CHANGE_PRICE = redisServer.get( Rediskey );

			List<String> list=new ArrayList<>(  );
			int d=0;
			while (true) {
               /* Long nowTIme = DateUtils.getCurrentDataLong();
                LocalDateTime time = DateUtils.getDateTimeOfTimestamp( nowTIme-d );
                int minu = time.getMinute()/5;
                String timePart = DateUtils.localDateTimeFormatString(time,DateUtils.format_ymdh);
                timePart += minu < 10 ? "0"+minu:minu;*/
				LocalDateTime timeres2 = DateUtils.getDateTimeOfTimestamp( nowTImeres-d );
				String lastRowKey = DateUtils.localDateTimeFormatString(timeres2,DateUtils.format_ymdhm);//当前时间转成分钟
				String rowKey = exchangeId+"@"+exchangeTransactionpairMiddle.getTransactionName()+"@"+lastRowKey;

				String API_SERVICE_TRADES  = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.API_SERVICE_K_ACTION_TABLE_NAME
						, HbaseTableUtils.API_SERVICE_K_ACTION_TABLE_NAME_FAMILY
						, HbaseTableUtils.API_SERVICE_K_ACTION_QUALIFIER
						, rowKey
				);
				if(API_SERVICE_TRADES != null){
					list.add( API_SERVICE_TRADES );
				}
				if ( d > 86400000) {
					break;
				}
				d = d + 60000;
			}

			BigDecimal allAmount=new BigDecimal( 0 );
            BigDecimal allAmountTem=new BigDecimal( 0 );
            TradesToKLine tradesToKLine;
			for(int i=0;i<list.size();i++){
				String object=list.get( i );
				if (object!=null){
                    Object listArray = new JSONTokener(object).nextValue();
                    if(listArray instanceof  net.sf.json.JSONArray){//老数据兼容问题
                        JSONArray jsonArray = JSON.parseArray(object);
                        allAmountTem = new BigDecimal(jsonArray.getString(5));
                        allAmount=allAmount.add(allAmountTem);
                    }else{
                        TradesToKLine five= JSON.parseObject( object, TradesToKLine.class );
                        if(five!=null && five.getVolume()!=null){
                            allAmount=allAmount.add( new BigDecimal( five.getVolume() ));
                        }
                    }
				}
			}
			if (API_SERVICE_K_ACTION_CHANGE_PRICE != null) {
				ApiWebSocketVo vo = new ApiWebSocketVo();

				JSONObject jsonObject = JSON.parseObject( API_SERVICE_K_ACTION_CHANGE_PRICE );
				jsonObject.put( "allAmount", allAmount);
				/*vo.setData( jsonObject );
				vo.setExplain( "k线表头数据");
				vo.setType( "5" );
				return JSON.toJSONString( vo );*/
				resultVo.setData( jsonObject );
				resultVo.setCode( ApiResultCodeUtils.BASE_SUCCESS.getCode());
				resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
				resultVo.setTradeId(LogTrace.getTrace().getTraceId());
				return resultVo;
			}
		}catch (Exception e){
			e.printStackTrace();
			LogTrace.error("k线表头数据",e);
		}
		resultVo.setCode( ApiResultCodeUtils.SYSTEM_NULL.getCode());
		resultVo.setMessage(ApiResultCodeUtils.SYSTEM_NULL.getMsg());
		resultVo.setTradeId(LogTrace.getTrace().getTraceId());
		return resultVo;
	}

	/**
	 * k线数据-历史交易
	 */
	@ApiOperation(value = "k线数据-历史交易" , notes = "k线数据-历史交易")
	@PostMapping("tranes")
	public ApiResultVo tranes(@RequestParam(value = "exchangeId", required = false) Integer exchangeId,@RequestParam(value = "transactionId", required = false) Integer transactionId) {
		ApiResultVo resultVo = new ApiResultVo();
		try {

			ExchangeTransactionpairMiddle query = new ExchangeTransactionpairMiddle();
			query.setTransactionId(transactionId);
			query.setExchangeId( exchangeId );
			ExchangeTransactionpairMiddle exchangeTransactionpairMiddle = exchangeTransactionpairMiddleMapper.selectByEntity(query);
			if(exchangeTransactionpairMiddle == null || !exchangeTransactionpairMiddle.getEnableFlag()){
				LogTrace.info("tranes","exchangeTransactionpairMiddle",transactionId+"查询不可用");
				resultVo.setCode( ApiResultCodeUtils.SYSTEM_NULL.getCode());
				resultVo.setMessage(ApiResultCodeUtils.SYSTEM_NULL.getMsg());
				resultVo.setTradeId(LogTrace.getTrace().getTraceId());
				return resultVo;
			}
			//redis
			String Rediskey = RedisKeysUtils.API_SERVICE_TRADES + "@" + exchangeId + "@" + exchangeTransactionpairMiddle.getTransactionName();
			String API_SERVICE_TRADES = redisServer.get( Rediskey );
			//hbase
			/*if (API_SERVICE_TRADES == null) {
				int d = 0;
				while (true) {
					Long nowTIme = DateUtils.getCurrentDataLong();
					LocalDateTime time = DateUtils.getDateTimeOfTimestamp( nowTIme - d );
					String rowKey = DateUtils.localDateTimeFormatString( time, DateUtils.format_ymdhm ) + "@" + exchangeId + "@" + exchangeTransactionpairMiddle.getTransactionName();
					;
					API_SERVICE_TRADES = hbaseBaseQueryComponent.selectByQualifierData( HbaseTableUtils.API_SERVICE_TRADES_TABLE_NAME
							, HbaseTableUtils.API_SERVICE_TRADES_TABLE_NAME_FAMILY
							, HbaseTableUtils.API_SERVICE_TRADES_QUALIFIER
							, rowKey
					);
					//只取一天内最新数据
					if (API_SERVICE_TRADES != null || d > 86400000) {
						break;
					}
					d = d + 60000;
				}
			}*/
			if (API_SERVICE_TRADES != null) {
				List<ApiTradesHistoryVo> tradesHistoryVos = new ArrayList<>();
				ApiTradesHistoryVo apiTradesHistoryVo;
				List<TradesHistory> tradesHistoryList = JSON.parseArray(API_SERVICE_TRADES,TradesHistory.class);
				if(tradesHistoryList!=null && tradesHistoryList.size()>0){
					for(TradesHistory tradesHistory :tradesHistoryList){
						apiTradesHistoryVo = new ApiTradesHistoryVo();
						apiTradesHistoryVo.setAmount(tradesHistory.getAmount().stripTrailingZeros().toPlainString());
						apiTradesHistoryVo.setPrice(tradesHistory.getPrice().stripTrailingZeros().toPlainString());
						apiTradesHistoryVo.setTimestamp(tradesHistory.getTimestamp());
						apiTradesHistoryVo.setBuyOrSellFlag(tradesHistory.getSide());
						tradesHistoryVos.add(apiTradesHistoryVo);
					}
				}
				resultVo.setData( tradesHistoryVos );
				resultVo.setCode( ApiResultCodeUtils.BASE_SUCCESS.getCode());
				resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
				resultVo.setTradeId(LogTrace.getTrace().getTraceId());
				return resultVo;
			}
		}catch (Exception e){
			e.printStackTrace();
			LogTrace.error("k线数据-历史交易",e);
		}
		return  resultVo;
	}

}
